from time import strftime
#print strftime("%Y-%m-%d %H:%M:%S")
import index_utility_module
import sys
import TokenMatcher
from DatabaseConnector import connection

_DEBUG_ = True

class DiagMatrix:
    def __new__(cls, *args, **kargs):
        if cls.instance is None:
            cls.instance = object.__new__(cls, *args, **kargs)
        return cls.instance   
    
    def __init__(self):
        self.idx = index_utility_module.IndexUtility()
        self.result_matrix = {}
        
    def getDiagMatrixInstant(self, diag):
        diag_token = diag.split()
        conc_list = []
    
    ## Loading zone    
        dictionary = {}
        cursor = connection.cursor()
        if _DEBUG_:
            sys.stderr.write("Loading dictionary..")
        cursor.execute("select `Concept ID`, `Description ID` from snomed.sct_descriptions_20070731")
        
        for i, tuple in enumerate(cursor):
            if _DEBUG_:
                if i % 10000 == 0:
                    sys.stderr.write(".")
            dictionary[tuple[1]] = tuple[0]
        if _DEBUG_:
            sys.stderr.write(" %s entries\n" % i)
    ################
    
    #    print strftime("%Y-%m-%d %H:%M:%S")
        for ((s, e), ids) in TokenMatcher.match_sentence(diag_token):
            for id in ids:
    #            print id
                if conc_list.count(dictionary[id]) == 0:
                    conc_list.append(dictionary[id])
#        print "Concept id list:"
#        print len(conc_list)
#        print conc_list
    #        print conceptid
        self.idx.IndexInstance(conc_list)
    
    def getResultMatrix(self, patientids):
        for tuple in patientids:
            if self.idx.concept_idx.has_key(tuple[1]):
                if self.result_matrix.has_key(tuple[0]) == False:
                    self.result_matrix[tuple[0]] = []
                    self.result_matrix[tuple[0]].append(tuple[1])
                elif self.result_matrix[tuple[0]].count(tuple[1]) == 0: 
                    self.result_matrix[tuple[0]].append(tuple[1])
        
    #    print result_matrix
    #    print strftime("%Y-%m-%d %H:%M:%S")
    
if __name__ == "__main__":
    matrix = DiagMatrix()
    ls = matrix.getDiagMatrixInstant("spleen")
    cursor = connection.cursor()
    cursor.execute("SELECT r.`PatientID`, r.`RequestID` FROM hosrep.request_table r where patientid = 233841")
    matrix.getResultMatrix(cursor)
    print matrix.result_matrix